package com.demo.crm.springboot3security.exception;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.validation.ValidationException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ControllerAdvice
@RequiredArgsConstructor
public class GlobalExceptionHandler {

    private final MeterRegistry meterRegistry;
    private final Map<Class<? extends Exception>, Counter> exceptionCounters = new ConcurrentHashMap<>();

    @ExceptionHandler(ValidationException.class)
    public ResponseEntity<Map<String, Object>> handleValidationException(ValidationException e) {
        incrementExceptionCounter(e);
        Map<String, Object> response = new HashMap<>();
        response.put("error", "验证失败");
        response.put("message", e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleIllegalArgumentException(IllegalArgumentException e) {
        incrementExceptionCounter(e);
        Map<String, Object> response = new HashMap<>();
        response.put("error", "参数错误");
        response.put("message", e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        incrementExceptionCounter(e);
        log.error("系统异常", e);
        Map<String, Object> response = new HashMap<>();
        response.put("error", "系统错误");
        response.put("message", "请联系系统管理员");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }

    @ExceptionHandler(FormRelationException.class)
    public ResponseEntity<Map<String, Object>> handleFormRelationException(FormRelationException ex) {
        log.error("表单关系错误: ", ex);
        Map<String, Object> response = new HashMap<>();
        response.put("error", "表单关系错误");
        response.put("message", ex.getMessage());
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    @ExceptionHandler(FormRelationException.RelationNotFoundException.class)
    public ResponseEntity<Map<String, Object>> handleRelationNotFoundException(
            FormRelationException.RelationNotFoundException ex) {
        log.error("未找到表单关系: ", ex);
        Map<String, Object> response = new HashMap<>();
        response.put("error", "未找到表单关系");
        response.put("message", ex.getMessage());
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
    }

    @ExceptionHandler(FormRelationException.InvalidRelationException.class)
    public ResponseEntity<Map<String, Object>> handleInvalidRelationException(
            FormRelationException.InvalidRelationException ex) {
        log.error("无效的表单关系: ", ex);
        Map<String, Object> response = new HashMap<>();
        response.put("error", "无效的表单关系");
        response.put("message", ex.getMessage());
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    @ExceptionHandler(FormRelationException.DuplicateRelationException.class)
    public ResponseEntity<Map<String, Object>> handleDuplicateRelationException(
            FormRelationException.DuplicateRelationException ex) {
        log.error("重复的表单关系: ", ex);
        Map<String, Object> response = new HashMap<>();
        response.put("error", "重复的表单关系");
        response.put("message", ex.getMessage());
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
    }

    private void incrementExceptionCounter(Exception e) {
        Counter counter = exceptionCounters.computeIfAbsent(
            e.getClass(),
            exceptionClass -> Counter.builder("exception.count")
                    .tag("type", exceptionClass.getSimpleName())
                    .description("异常计数器")
                    .register(meterRegistry)
        );
        counter.increment();
    }
} 